package com.yidi.system.repository;

import com.yidi.common.core.Repository.BaseRepository;
import com.yidi.common.core.domain.entity.SysDept;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author ：Xn
 * @ClassName: SysDeptRepository
 * @date ：2021-10-19 14:41
 * @describe ：部门
 */
@Repository
public interface SysDeptRepository extends BaseRepository<SysDept,Long> {

    @Query(nativeQuery = true, value = "select d.id from sys_dept d left join sys_role_dept rd on d.id = rd.dept_id"
            +" where rd.role_id = ?1 and d.id not in (select d.parent_id from sys_dept d inner join sys_role_dept rd on d.id = rd.dept_id and rd.role_id = ?1)"
            +" order by d.parent_id, d.order_num")
    List<Integer> selectDeptListByRoleId(Long roleId);

    SysDept findByDeptNameAndParentId(String deptName, Long parentId);

    @Query(nativeQuery = true, value = "select count(*) from sys_dept where status = 0 and remove_status = 0 and find_in_set(?1, ancestors)")
    Integer selectNormalChildrenDeptById(Long deptId);

    @Query(nativeQuery = true, value = "select * from sys_dept where find_in_set(?1, ancestors)")
    List<SysDept> selectChildrenDeptById(Long deptId);

    @Query(nativeQuery = true, value = "select count(1) from sys_dept where remove_status = '0' and parent_id = ?1 limit 1")
    int hasChildByDeptId(Long deptId);

    @Query(nativeQuery = true, value = "select count(1) from sys_user where dept_id = ?1 and remove_status = '0'")
    int checkDeptExistUser(Long deptId);
}
